from datetime import datetime
from enum import Enum, unique
from typing import Optional, List
from .base_model import BaseEntity

from sqlalchemy import VARCHAR, Integer, Text
from sqlmodel import Field, Relationship, SQLModel


@unique
class DownlinkFrequencyBand(Enum):
    """5G下行频段枚举(单位MHz)"""

    BAND_110_2130 = "110~2130"
    BAND_4800_4900 = "4800~4900"
    BAND_3500_3600 = "3500~3600"
    BAND_3400_3500 = "3400~3500"
    BAND_2515_2675 = "2515~2675"
    BAND_2320_2370 = "2320~2370"
    BAND_2130_2145 = "2130~2145"
    BAND_2110_2130 = "2110~2130"
    BAND_2010_2025 = "2010~2025"
    BAND_1885_1915 = "1885~1915"

    def __str__(self):
        return self.value


class BaseStation(BaseEntity, table=True):
    __tablename__ = "base_stations"
    __table_args__ = {"comment": "基站表"}

    name: str = Field(description="基站名称")
    longitude: float = Field(description="经度")
    latitude: float = Field(description="纬度")
    address: Optional[str] = Field(description="基站地址")
    is_rooftop: bool = Field(description="是否天面：False-天面 True-地面（default）")
    network_type: Optional[str] = Field(
        default=None, max_length=50, description="网络制式"
    )
    frequency_range: Optional[str] = Field(
        default=None, max_length=50, description="频率范围(MHz)"
    )
    sector: Optional[str] = Field(default=None, description="扇区")
    tower_type: Optional[str] = Field(
        default=None, max_length=50, description="杆塔类型"
    )
    height: Optional[float] = Field(default=None, description="高度")
    vertical_distance: Optional[float] = Field(
        default=None, max_length=20, description="垂直距离"
    )
    town: Optional[str] = Field(default=None, max_length=50, description="镇区")
    division: Optional[str] = Field(
        default=None, max_length=50, description="公司区域划分"
    )

    nr_freq_records: List["NRFreqRecord"] = Relationship(
        back_populates="base_station", cascade_delete=True
    )
    lte_freq_records: List["LTEFreqRecord"] = Relationship(
        back_populates="base_station", cascade_delete=True
    )


class NRFreqRecord(BaseEntity, table=True):
    __tablename__ = "nr_freq_records"
    __table_args__ = {"comment": "5G基站频率记录表"}

    location: str = Field(
        description="点位描述（如基站西北侧/北侧等）",
    )
    horizontal_distance: Optional[float] = Field(description="水平距离(m)")
    vertical_distance: Optional[float] = Field(description="垂直距离(m)")
    operator: str = Field(default="电信公司", description="运营商")
    downlink_band: Optional[str] = Field(
        description="下行频段(MHz)必须从预定义选项中选择",
    )
    band_monitoring_result: Optional[float] = Field(description="频段监测结果")
    device_model: str = Field(default="iQool11", description="设备型号")
    device_count: int = Field(default=1, description="设备数量(个)")
    total_consumption: Optional[float] = Field(description="消耗总流量(G)")
    max_rate: Optional[float] = Field(description="最高速率(M/s)")
    probe_distance: float = Field(description="探头距终端距离(m)")
    data_transmission: bool = Field(default=True, description="数据传输（是/否）")
    video_interaction: bool = Field(default=False, description="视频交互")
    game_entertainment: bool = Field(default=False, description="游戏娱乐")
    virtual_shopping: bool = Field(default=False, description="虚拟购物")
    smart_medicine: bool = Field(default=False, description="智慧医疗")
    industrial_application: bool = Field(default=False, description="工业应用")
    car_internet: bool = Field(default=False, description="车联网")
    other_application: bool = Field(default=False, description="其他应用")
    is_on_ground: bool = Field(
        default=True,
        description="是否位于地面（是/否）",
    )
    longitude: Optional[float] = Field(description="经度(°)")
    latitude: Optional[float] = Field(description="纬度(°)")
    remarks: Optional[str] = Field(description="备注信息")
    image_path: Optional[str] = Field(
        description="图片文件路径及名称",
    )
    record_datetime: datetime = Field(
        description="检测时间",
    )
    recorder: Optional[str] = Field(description="检测人")
    base_station_id: int = Field(
        foreign_key="base_stations.id",
        nullable=False,
        description="基站ID",
        ondelete="CASCADE",
    )

    base_station: BaseStation = Relationship(back_populates="nr_freq_records")


class LTEFreqRecord(BaseEntity, table=True):
    __tablename__ = "lte_freq_records"
    __table_args__ = {"comment": "4G基站频率记录表"}
    point_number: str = Field(description="点位编号(如1#、2#等)")
    point_description: str = Field(
        description="点位描述(如7F医学楼天面北侧等)",
    )
    line_max: float = Field(description="线最大值")
    line_min: float = Field(description="线最小值")
    result_1: float = Field(description="监测结果1(V/m)")
    result_2: float = Field(description="监测结果2(V/m)")
    result_3: float = Field(description="监测结果3(V/m)")
    result_4: float = Field(description="监测结果4(V/m)")
    result_5: float = Field(description="监测结果5(V/m)")
    result_avg: float = Field(description="监测结果平均值(V/m)")
    standard_deviation: float = Field(description="标准偏差")
    mobile_value: float = Field(description="移动分频(V/m)")
    unicom_value: float = Field(description="联通分频(V/m)")
    telecom_value: float = Field(description="电信分频(V/m)")
    telegraph_value: float = Field(description="铁塔分频(V/m)")
    other_value: Optional[float] = Field(description="其他分频(V/m)")
    is_large_value_point: bool = Field(default=False, description="是否大值监测点")
    longitude: float = Field(description="经度(°)")
    latitude: float = Field(description="纬度(°)")
    image_path: Optional[str] = Field(description="图片文件路径及名称")
    remarks: Optional[str] = Field(description="备注信息")
    record_datetime: datetime = Field(
        description="检测时间",
    )
    recorder: Optional[str] = Field(description="检测人")
    base_station_id: int = Field(
        foreign_key="base_stations.id",
        nullable=False,
        description="基站ID",
        ondelete="CASCADE",
    )
    base_station: BaseStation = Relationship(back_populates="lte_freq_records")

    def __repr__(self):
        return f"<MedicalBuildingEMFMonitoring(point_number='{self.point_number}', description='{self.point_description}')>"
